<?php

class csSystem {
	
	public $tpl_tbl;
	public $tpl_vars;
	
	public $charset;
	public $lang;
	
	public $cs_params;
	public $pass_params;
	
	public $db;
	public $navbar;
	
	protected $db_user;
	protected $db_host;
	protected $db_pass;
	protected $db_name;
	protected $sqls;
	
	protected $valid_actions;
	protected $content_tpl;
	public $default_action;
	public $action;
	
	public function __construct() {
		//uruchomienie kolejki ostrzezen
		global $warning_queue;
		$warning_queue = new csWarningQueue();
		
		//uruchomienie systemu templejtow
		$this -> tpl_vars = array();
		$this -> tpl_tbl = array();
		global $tpl_system;
		$tpl_system = new csTpl();
		$GLOBALS['tpl_system'] -> tpl_tbl = & $this -> tpl_tbl;
		$GLOBALS['tpl_system'] -> tpl_vars = & $this -> tpl_vars;
		
		//uruchomienie bazy
		$this -> db = new csMySql();
		
		//obsluga naglowka html
		$this -> html_head = new csHtmlHead($this);
		
		//pobranie parametrow urla, posta itp.
		$this -> cs_params = get_request();
		//ustalenie ktore parametry przekazywac dalej w linkach
		$this -> pass_params = array(
			'debug',
			'action'
		);
		
		//ustalenie mozliwych do wykonania akcji glownych
		$this -> valid_actions = array(
			'player',
			'players',
			'news',
			'admin'
		);
		
		//ustawienie trybu debugowania jesli jest taki parametr w urlu
		if (isset($this -> cs_params['debug']) && $this -> cs_params['debug']) {
			$this -> db -> debug_mode = true;
			$GLOBALS['tpl_system'] -> debug_mode = true;
		}
		
		//narazie pusty glowny templejt
		$this -> tpl_vars['content_tpl'] = & $this -> content_tpl;
		$this -> content_tpl = null;
		//TODO - ustawic wszystkie wartosci domyslne	}

	protected function set_core_setup() {
		require_once(CS_INCL_DIR . 'core_setup.php');
		
		if (! is_array($conf_tbl)) {
			$conf_tbl = array(
			);
		}
		
		$parray = array(
			'db_user', 
			'db_host', 
			'db_pass', 
			'db_name',
			'sqls'
		);
		//TODO itd - wszystkie modyfikowalne		

		foreach ($parray as $pind => $pname) {
			if (isset($conf_tbl[$pname])) {
				$this -> $pname = $conf_tbl[$pname];
			}
		}
		
		$tarray = array(
			'html_header_tpl', 
			'main_menu_tpl',
			'menu_element_tpl',
			'navbar_tpl',
			'page_header_tpl',
			'players_tpl',
			'toplevel_tpl',
			'warning_tpl'
		);
		
		foreach ($tarray as $tind => $tname) {
			if (isset($tpl_tbl[$tname])) {
				$this -> tpl_tbl[$tname] = $tpl_tbl[$tname];
			} else {
				$this -> tpl_tbl[$tname] = null;
			}
		}
	}

	protected function set_user_setup() {
		//TODO configuracja usera pobrana z bazy narazie na sztywno		//$this -> site_name = 'Club-Site';
	}

	public function get_translations($lang, $default = false) {
		include_once ('translations/' . $lang . '.php');
		
		if (isset($trans_tbl)) {
			$ind = ($default ? '' : $lang);
			
			global $trans_tbl;
			
			$trans_tbl[$ind] = $trans_tbl;
		}
	}

	public function set_lang() {
		//TODO narazie na sztywno		$this -> lang = 'pl_PL';
		$this -> charset = 'utf-8';
		
		$this -> db -> query('SET NAMES utf8');
		
	//TODO get_translations	}

	public function doit() {
		try {
			$this -> pre_action();
			$this -> before_action();
			
			$this -> action();
			
			$this -> after_action();
			$this -> post_action();
			
		} catch (csErrorException $e) {
			echo "Error<br />\n";
			if (defined('CS_ENABLE_DEBUG') && CS_ENABLE_DEBUG) {
				echo "Message: ", $e -> get_mysql_error(), "<br />\n";
				echo "Query: ", $e -> get_mysql_query(), "<br />\n";
				echo "Code: ", $e -> getCode(), "<br />\n";
			}
			exit();
			//TODO ....
			//echo $e -> getMessage() . " " . $e -> getCode();			//$this -> error();
		} catch (csMysqlException $e) {
			echo "Error<br />\n";
			if (defined('CS_ENABLE_DEBUG') && CS_ENABLE_DEBUG) {
				echo "Message: ", $e -> get_mysql_error(), "<br />\n";
				echo "Query: ", $e -> get_mysql_query(), "<br />\n";
				echo "Code: ", $e -> getCode(), "<br />\n";
			}
			exit();//TODO - bez exita
		} catch (csException $e) {
			echo "Error<br />\n";
			if (defined('CS_ENABLE_DEBUG') && CS_ENABLE_DEBUG) {
				echo "Message: ", $e -> getMessage(), "<br />\n";
				echo "Code: ", $e -> getCode(), "<br />\n";
			}
			exit();
		}
		
		try {
			dvar($this -> tpl_vars, 'tpl_vars');			$GLOBALS['tpl_system'] -> display($this -> tpl_tbl['toplevel_tpl']);
		
		} catch (csErrorException $e) {
			//TODO cos wyswietlic zamiast templejta		}
	}

	protected function pre_action() {
		$this -> set_core_setup();
		
		try {
			$this -> db -> connect(array(
				'db_host' => $this -> db_host,
				'db_user' => $this -> db_user,
				'db_pass' => $this -> db_pass
			));
			
			$this -> db -> select_db($this -> db_name);
			
		} catch (csMysqlException $e) {
			throw new csFatalException(translate('Database error'), 888013);
		}
		
		if (!isset($this -> cs_params['action']) || !in_array($this -> cs_params['action'], $this -> valid_actions)) {
			$this -> action = $this -> default_action;
		} else {
			$this -> action = $this -> cs_params['action'];
		}
		
		$this -> tpl_vars['cs_params'] =& $this -> cs_params;
		$this -> tpl_vars['pass_params'] =& $this -> pass_params;
		 
	}

	protected function before_action() {
		$this -> set_user_setup();
		
		$this -> set_lang();
		
		$this -> get_menu_tbl();
		
		$this -> navbar = new csNavbar();
		$this -> navbar -> add(translate('Main page'), $_SERVER["SCRIPT_NAME"].url_params($this -> cs_params, array('debug')));
	}

	protected function action() {
		$cs_action = "action_" . $this -> action;
		
		if (is_callable(array('csSystem', $cs_action))) {
			$this -> $cs_action();
		} else {
			$this -> action_news();
		}
		
	}

	protected function after_action() {
		//TODO - z tym css'em napewno inaczej
		$this -> html_head -> css_tbl = array('lay/cs.css');
		$this -> html_head -> set_header();
		
		$this -> assign_tpl_vars();
	}

	protected function post_action() {
	
	}

	public function error() {
		//TODO main_tpl = error_tpl	}

	protected function assign_tpl_vars() {
		$tvarr = array(
			'site_name', 
			'action', 
			'lang'
		);
		
		foreach ($tvarr as $tvind => $tvname) {
			if (isset($this -> $tvname)) {
				$this -> tpl_vars[$tvname] = $this -> $tvname;
			}
		}
		
		$this -> tpl_vars['navbar_elements'] = $this -> navbar -> element_tbl;
		$this -> tpl_vars['navbar_delimiter'] = $this -> navbar -> delimiter;
		$this -> tpl_vars['left_menu_tbl'] = $this -> left_menu_tbl;
		$this -> tpl_vars['topmenu_obj'] = $this -> topmenu_obj;
	}

	protected function get_menu_tbl() {
		$this -> menu_tbl = array();
		$this -> left_menu_tbl = array();
		$this -> topmenu_obj = null;
		
		$menu_types = $this -> db -> query_row_tbl('SELECT * FROM csmenutype WHERE status_mt IS NOT NULL ORDER BY sort_mt DESC');
		if (!$menu_types) return;
		
		$menu_elements = $this -> db -> query_row_tbl('SELECT * FROM csmenuelement WHERE status_me IS NOT NULL ORDER BY sort_me DESC');
		
		foreach ($menu_types as $menu_row) {
			$this -> menu_tbl[$menu_row['id_mt']] = new csMenu(array(
				'menu_name' => $menu_row['name_mt'],
				'element_tpl' => $this -> tpl_tbl['menu_element_tpl'],
				'sort' => $menu_row['sort_mt']
			));
			
			if ($menu_row['type_mt'] == CS_TOPMENU_TYPE) {
				$this -> menu_tbl[$menu_row['id_mt']] -> menu_div_html_options = 'class="top-menu"';
				$this -> topmenu_obj =& $this -> menu_tbl[$menu_row['id_mt']];
			
			} else if ($menu_row['type_mt'] == CS_LEFTMENU_TYPE) {
				$this -> menu_tbl[$menu_row['id_mt']] -> menu_div_html_options = 'class="left-menu" id="left-menu-'.$menu_row['id_mt'].'"';
				$this -> left_menu_tbl[$menu_row['id_mt']] =& $this -> menu_tbl[$menu_row['id_mt']];
			}
		}
		if (!$menu_elements) return;
		$req_str = $_SERVER["SCRIPT_NAME"] . ($_SERVER['QUERY_STRING'] ? '?' : '') . $_SERVER['QUERY_STRING'];
		//$this -> active_menu_element = null;
		//$this -> auto_navigation_path = null;
		
		foreach ($menu_elements as $element) {
			if (!isset($this -> menu_tbl[$element['csmenutype_id_mt']])) continue;
			if (!isset($element['class_me']) || !class_exists('csMenuElement'.$element['class_me'])) {
				$classname = 'csMenuElement'.CS_MENU_DIRECT;
			} else {
				$classname = 'csMenuElement'.$element['class_me'];
			}
			
			$element_obj = new $classname($element, $this -> cs_params, $this -> pass_params);
			
			$this -> menu_tbl[$element['csmenutype_id_mt']] -> add_element($element_obj);
			//TODO - ten warunek jest kiepski
			if ($element_obj -> url == $req_str) {
				$this -> active_menu_element = $element_obj;
				$element_obj -> active = true;
				$this -> menu_tbl[$element['csmenutype_id_mt']] -> active_element_id = $element_obj -> get_id();
				//$this -> auto_navigation_path = $this -> menu_tbl[$element['csmenutype_id_mt']] -> get_navigation_path();
			}
		}
		
		foreach ($this -> menu_tbl as &$menu_obj) {
			$menu_obj -> regularize();
		}
	}
	
	public function get_menu_element($element_id) {
		foreach ($this -> menu_tbl as &$menu_obj) {
			if ($elem = $menu_obj -> get_element($element_id)) return $elem;
		}
		return null;
	}
	
	
	protected function prepare_admin_menu() {
		//TODO - obsluga bledow
		$this -> admin_menu = new csMenu(array(
			'recursion_limit' => $this -> menu_recursion_limit,
			'element_tpl' => $this -> tpl_tbl['menu_element_tpl']
		));
		
		$this -> admin_menu -> add_element(new csMenuElement(array(
			'id' => 'seasons', 
			'name' => translate('Seasons'), 
			'url' => $_SERVER["SCRIPT_NAME"] . url_params($this -> cs_params, $this -> pass_params, array(
				'action' => 'admin', 
				'mod' => 'season'
			)),
			'sort' => 2000
		)));
		
		$this -> admin_menu -> add_element(new csMenuElement(array(
			'id' => 'teams', 
			'name' => translate('Teams'), 
			'url' => $_SERVER["SCRIPT_NAME"] . url_params($this -> cs_params, $this -> pass_params, array(
				'action' => 'admin', 
				'mod' => 'team'
			)),
			'sort' => 1900
		)));
		
		$this -> admin_menu -> add_element(new csMenuElement(array(
			'id' => 'teams1', 
			'name' => translate('Own'), 
			'url' => $_SERVER["SCRIPT_NAME"] . url_params($this -> cs_params, $this -> pass_params, array(
				'action' => 'admin', 
				'mod' => 'team',
				'status_tm' => '1'
			)),
			'parent' => 'teams',
			'sort' => 100
		)));
		
		$this -> admin_menu -> add_element(new csMenuElement(array(
			'id' => 'teams1', 
			'name' => translate('Owns'), 
			'url' => $_SERVER["SCRIPT_NAME"] . url_params($this -> cs_params, $this -> pass_params, array(
				'action' => 'admin', 
				'mod' => 'team',
				'status' => '1'
			)),
			'parent' => 'teams',
			'sort' => 100
		)));
		$this -> admin_menu -> add_element(new csMenuElement(array(
			'id' => 'teams0', 
			'name' => translate('Others'), 
			'url' => $_SERVER["SCRIPT_NAME"] . url_params($this -> cs_params, $this -> pass_params, array(
				'action' => 'admin', 
				'mod' => 'team',
				'status' => '0'
			)),
			'parent' => 'teams',
			'sort' => 80
		)));
		
		$this -> admin_menu -> add_element(new csMenuElement(array(
			'id' => 'players', 
			'name' => translate('Players'), 
			'url' => $_SERVER["SCRIPT_NAME"] . url_params($this -> cs_params, $this -> pass_params, array(
				'action' => 'admin', 
				'mod' => 'player'
			)),
			'sort' => 1800
		)));
		
		$this -> admin_menu -> add_element(new csMenuElement(array(
			'id' => 'players-1', 
			'name' => translate('Not active'), 
			'url' => $_SERVER["SCRIPT_NAME"] . url_params($this -> cs_params, $this -> pass_params, array(
				'action' => 'admin', 
				'mod' => 'player',
				'id_tm' => '-1'
			)),
			'parent' => 'players',
			'sort' => -10
		)));
		
		$this -> admin_menu -> add_element(new csMenuElement(array(
			'id' => 'leagues', 
			'name' => translate('Leagues'), 
			'url' => $_SERVER["SCRIPT_NAME"] . url_params($this -> cs_params, $this -> pass_params, array(
				'action' => 'admin', 
				'mod' => 'league'
			)),
			'sort' => 1700
		)));
		
		$this -> admin_menu -> add_element(new csMenuElement(array(
			'id' => 'tables', 
			'name' => translate('Tables'), 
			'url' => $_SERVER["SCRIPT_NAME"] . url_params($this -> cs_params, $this -> pass_params, array(
				'action' => 'admin', 
				'mod' => 'table'
			)),
			'sort' => 1600
		)));
		
		$this -> admin_menu -> add_element(new csMenuElement(array(
			'id' => 'series', 
			'name' => translate('Schedule'), 
			'url' => $_SERVER["SCRIPT_NAME"] . url_params($this -> cs_params, $this -> pass_params, array(
				'action' => 'admin', 
				'mod' => 'series'
			)),
			'sort' => 1500
		)));
		
		
		$this -> admin_menu -> add_element(new csMenuElement(array(
			'id' => 'matches', 
			'name' => translate('Matches'), 
			'url' => $_SERVER["SCRIPT_NAME"] . url_params($this -> cs_params, $this -> pass_params, array(
				'action' => 'admin', 
				'mod' => 'match'
			)),
			'sort' => 1400
		)));
		
		$team_list = $this -> db -> query_row_tbl($this -> sqls['get_own_team_list'], 'id_tm');
		$season_list = $this -> db -> query_row_tbl($this -> sqls['get_season_list'], 'id_sn');
		$league_list = $this -> db -> query_row_tbl($this -> sqls['get_league_list'], 'id_lg');
		
		$season_league_list = array();
		foreach ($league_list as $idlg => $lobj) {
			if (!isset($season_league_list[$lobj['csseason_id_sn']])) {
				$season_league_list[$lobj['csseason_id_sn']] = array();
			}
			$season_league_list[$lobj['csseason_id_sn']][] = $lobj;
		}
		
		if ($team_list) {
			foreach ($team_list as $team) {
				$this -> admin_menu -> add_element(new csMenuElement(array(
					'id' => 'players'.$team['id_tm'], 
					'name' => $team['name_tm'], 
					'url' => $_SERVER["SCRIPT_NAME"] . url_params($this -> cs_params, $this -> pass_params, array(
						'action' => 'admin', 
						'mod' => 'player',
						'id_tm' => $team['id_tm']
					)),
					'parent' => 'players'
				)));
				
				$this -> admin_menu -> add_element(new csMenuElement(array(
					'id' => 'matches'.$team['id_tm'], 
					'name' => $team['name_tm'], 
					'url' => $_SERVER["SCRIPT_NAME"] . url_params($this -> cs_params, $this -> pass_params, array(
						'action' => 'admin', 
						'mod' => 'match',
						'id_tm' => $team['id_tm']
					)),
					'parent' => 'matches'
				)));
			}
			
			$this -> admin_menu -> add_element(new csMenuElement(array(
				'id' => 'matches0', 
				'name' => translate('Other matches'), 
				'url' => $_SERVER["SCRIPT_NAME"] . url_params($this -> cs_params, $this -> pass_params, array(
					'action' => 'admin', 
					'mod' => 'match',
					'id_tm' => '0'
				)),
				'parent' => 'matches'
			)));
		}
		
		if ($season_list) {
			foreach ($season_list as $season) {
				$this -> admin_menu -> add_element(new csMenuElement(array(
					'id' => 'leagues'.$season['id_sn'], 
					'name' => translate('Season') . ' ' . $season['name_sn'], 
					'url' => $_SERVER["SCRIPT_NAME"] . url_params($this -> cs_params, $this -> pass_params, array(
						'action' => 'admin', 
						'mod' => 'league',
						'id_sn' => $season['id_sn']
					)),
					'parent' => 'leagues'
				)));
				
				$this -> admin_menu -> add_element(new csMenuElement(array(
					'id' => 'tables'.$season['id_sn'], 
					'name' => translate('Season') . ' ' . $season['name_sn'], 
					'url' => $_SERVER["SCRIPT_NAME"] . url_params($this -> cs_params, $this -> pass_params, array(
						'action' => 'admin', 
						'mod' => 'table',
					)),
					'parent' => 'tables'
				)));
				
				$this -> admin_menu -> add_element(new csMenuElement(array(
					'id' => 'series'.$season['id_sn'], 
					'name' => translate('Season') . ' ' . $season['name_sn'], 
					'url' => $_SERVER["SCRIPT_NAME"] . url_params($this -> cs_params, $this -> pass_params, array(
						'action' => 'admin', 
						'mod' => 'series',
					)),
					'parent' => 'series'
				)));
				
				if (isset($season_league_list[$season['id_sn']])) {
					foreach ($season_league_list[$season['id_sn']] as $slobj) {
						$this -> admin_menu -> add_element(new csMenuElement(array(
							'id' => 'tablesl'.$slobj['id_lg'], 
							'name' => $slobj['name_lg'] . ' ' .$slobj['name_tm'], 
							'url' => $_SERVER["SCRIPT_NAME"] . url_params($this -> cs_params, $this -> pass_params, array(
								'action' => 'admin', 
								'mod' => 'table',
								'id_lg' => $slobj['id_lg']
							)),
							'parent' => 'tables'.$season['id_sn']
						)));
						
						$this -> admin_menu -> add_element(new csMenuElement(array(
							'id' => 'seriesl'.$slobj['id_lg'], 
							'name' => $slobj['name_lg'] . ' ' .$slobj['name_tm'], 
							'url' => $_SERVER["SCRIPT_NAME"] . url_params($this -> cs_params, $this -> pass_params, array(
								'action' => 'admin', 
								'mod' => 'series',
								'id_lg' => $slobj['id_lg']
							)),
							'parent' => 'series'.$season['id_sn']
						)));
					}
				}
			}
		}
		
		$this -> admin_menu -> add_element(new csMenuElement(array(
			'id' => 'blank_menu', 
			'name' => translate('Menu management'),
			'sort' => 1301
		)));
		
		$this -> admin_menu -> add_element(new csMenuElement(array(
			'id' => 'menutype', 
			'name' => translate('Menu types'), 
			'url' => $_SERVER["SCRIPT_NAME"] . url_params($this -> cs_params, $this -> pass_params, array(
				'action' => 'admin', 
				'mod' => 'menutype'
			)),
			'sort' => 1300
		)));
		$this -> admin_menu -> add_element(new csMenuElement(array(
			'id' => 'menuelement', 
			'name' => translate('Menu elements'), 
			'url' => $_SERVER["SCRIPT_NAME"] . url_params($this -> cs_params, $this -> pass_params, array(
				'action' => 'admin', 
				'mod' => 'menuelement'
			)),
			'sort' => 1200
		)));
		
		$this -> admin_menu -> regularize();
	}
	
	protected function action_player() {
		
	}
	
	protected function action_players() {
		if (!isset($this -> cs_params['teamid'])) {
			 $id_tm = null;
		} else {
			$id_tm = $this -> cs_params['teamid'];
		}
		
		$team_data = $this -> get_team($id_tm);
		if (!$team_data) throw new csErrorException(translate('No such team'), 888013);
		
		$players = array(
			CS_GOALKEEPER_TYPE => array(),
			CS_DEFENDER_TYPE => array(),
			CS_MIDFIELDER_TYPE => array(),
			CS_FORWARD_TYPE => array()
		);
		
		$sth = $this -> db -> query_subst($this -> sqls['get_team_players'], array(
			'csteam_id_tm' => $team_data['id_tm']
		));
		
		while ($row = $this -> db -> fetch_array($sth)) {
			$players[$row['type_ps']][$row['id_pl']] = $this -> prepare_player($row);
		}
		
		$this -> tpl_vars['player_tbl'] = $players;
		$this -> tpl_vars['team_data'] = $team_data;
		//TODO - jjadu d[alej ... tzn wyswietlanie, m.in. ustawic tytuly
		
		$this -> navbar -> add(translate('Players'), $_SERVER["SCRIPT_NAME"].url_params($this -> cs_params, $this -> pass_params, array(
			'action' => 'players',
			'teamid' => $team_data['id_tm']
		)));
		$this -> content_tpl = $this -> tpl_tbl['players_tpl'];
	}
	
	protected function prepare_player($row) {
		if (isset($row['id_pl'])) {
			$row['player_url'] = $_SERVER["SCRIPT_NAME"] . url_params($this -> cs_params, $this -> pass_params, array(
				'action' => 'player', 
				'idpl' => $row['id_pl']
			));
		}
		
		return $row;
	}
	
	protected function action_news() {
		
	}
	
	protected function action_admin() {
		if (isset($this -> cs_params['mod']) && isset($this -> valid_admin_mods[$this -> cs_params['mod']])) {
			$mod = $this -> valid_admin_mods[$this -> cs_params['mod']];
		} else {
			$mod = $this -> default_admin_mod;
		}
		$this -> pass_params[] = 'mod';
		
		$this -> create_admin_obj($mod);
		//$this -> prepare_admin_menu();
		//$this -> admin_obj -> set_menu($this -> admin_menu);
		
		$this -> admin_obj -> cs_action($this);
		$this -> admin_obj -> doit();
		
		//$this -> tpl_tbl['toplevel_tpl'] = $this -> admin_obj -> toplevel_tpl;
	}
	
	protected function create_admin_obj($adminMod) {
		include_once(CS_ORM_DIR . '/csOrmBase.php');
		include_once(CS_ORM_DIR . '/csOrmPrint.php');
		include_once(CS_ORM_DIR . '/csOrmForm.php');
		include_once(CS_ORM_DIR . '/csOrmValidate.php');
		include_once(CS_ORM_DIR . '/csOrmField.php');
		include_once(CS_ORM_DIR . '/csOrmModel.php');
		include_once(CS_ORM_DIR . '/csOrm.php');
		
		$ormclass = 'csOrm'.$adminMod;
		
		$this -> admin_obj = new $ormclass($this -> db);
		
		$this -> admin_obj -> set_ref('cs_params', $this -> cs_params);
		$this -> admin_obj -> set_ref('pass_params', $this -> pass_params);
	}
	
	public function get_team($teamid = null) {
		if ($teamid === null) {
			$team = $this -> db -> query_row($this -> sqls['get_first_team']);
		} else {
			$team = $this -> db -> query_row_subst($this -> sqls['get_team'], array(
				'id_tm' => $teamid
			));
		}
		
		return $team;
	}
}

?>
